/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-26
 * Time: 21:14
 */
class Solution {
    public int minOperations(int[] nums, int x) {
        //滑动窗口
        int n = nums.length;
        int sum = 0;
        for (int num : nums) {
            sum += num;//求数组总和
        }
        int target = sum - x;//目标值
        //细节处理
        if (target < 0) {
            return -1;
        }

        int add = 0;//窗口数字的总和
        int len = -1;//窗口的长度

        for (int left = 0, right = 0; right < n; right++) {
            add += nums[right];//进窗口

            while (add > target) {//判断
                add -= nums[left++];//出窗口 -- 判断
            }
            if (add == target) {
                len = Math.max(len, right - left + 1);//更新结果
            }
        }
        return len == -1 ? -1 : n - len;//返回结果
    }
}
